from kafka import KafkaConsumer
import json

# 配置 Kafka 服务器地址
bootstrap_servers = ['localhost:9092']
# 要消费的主题
topic = 'test_topic'

# 创建 Kafka 消费者实例
consumer = KafkaConsumer(
    topic,
    bootstrap_servers=bootstrap_servers,
    value_deserializer=lambda m: json.loads(m.decode('utf-8'))
)

# 开始消费消息
try:
    for message in consumer:
        print(f"接收到消息: {message.value}")
except KeyboardInterrupt:
    print("停止消费消息")
finally:
    # 关闭消费者连接
    consumer.close()